import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import createVitePlugins from './vite/plugins'

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_ENV, VITE_APP_BASE_URL,VITE_APP_BASE_URL_WS} = env
  return {
    // 部署生产环境和开发环境下的URL。
    // 默认情况下，vite 会假设你的应用是被部署在一个域名的根路径上
    // 例如 https://www.ruoyi.vip/。如果应用被部署在一个子路径上，你就需要用这个选项指定这个子路径。例如，如果你的应用被部署在 https://www.ruoyi.vip/admin/，则设置 baseUrl 为 /admin/。
    base: VITE_APP_ENV === 'production' ? '/national-examination-ai/' : '/',
    plugins: createVitePlugins(env, command === 'build'),
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        // 设置路径
        '~': path.resolve(__dirname, './'),
        // 设置别名
        '@': path.resolve(__dirname, './src')
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    // vite 相关配置
    server: {
      port: 8081,
      cors: true,
      headers: {
        'Access-Control-Allow-Origin': '*',
        "Access-Control-Allow-Headers": "*",
        "Access-Control-Allow-Methods": "*",
      },
      host: false,
      open: false,
      // 配置服务器启动后的回调（获取实际端口）
      configureServer(server) {
        // 服务器启动完成后打印实际运行的端口
        server.httpServer?.once('listening', () => {
          const address = server.httpServer?.address()
          // 处理端口（可能是字符串形式的地址，这里取端口号）
          const actualPort = typeof address === 'object' && address ? address.port : 8081
          console.log(`\n🚀 开发服务器已启动，实际访问端口: ${actualPort}`)
          console.log(`📌 基础访问地址: http://localhost:${actualPort}\n`)
        })
      },
      proxy: {
        // https://cn.vitejs.dev/config/#server-proxy
        '/dev-api': {
          target: VITE_APP_BASE_URL,
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, ''),
          // 添加真实的访问日志记录
          configure: (proxy, options) => {
            proxy.on('proxyReq', (proxyReq, req, res) => {
              console.log(`API代理地址: request to: ${proxyReq.protocol}//${proxyReq.host}${proxyReq.path}`,`- 代理目标地址: ${options.target}\n`);
              console.log()
            });
          }
        },
        '/dev-ws': {
          target: VITE_APP_BASE_URL_WS,
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-ws/, ''),
          ws: true
        }

      }
    },
    //fix:error:stdin>:7356:1: warning: "@charset" must be the first rule in the file
    css: {
    //fix Deprecation Warning: The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0.
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler'
        }},
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          }
        ]
      }
    }
  }
})
